<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/1/15
 * Time: 16:12
 */

namespace app\common\cachemodel\zl7;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl7AiAnswerNumData extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl7_ai_answer_num_data';

    protected $cacheModel = 'ai_answer.user_ai';

    /**
     * 获取用户AI解答剩余次数
     * @param $uid
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getUserAiNum($uid)
    {
        $resData = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where('uid', $uid)->find();
                if (!$data)
                {
                    $data = [
                        'uid' => $uid,
                        'ai_num' => 0,
                        'total_num' => 0,
                        'use_num' => 0,
                        'admin_num' => 0,
                        'create_time' => time(),
                    ];
                    $this->insertGetId($data);
                } else
                {
                    $data = json_decode(json_encode($data, JSON_UNESCAPED_UNICODE), true);
                }
            }
            catch (\Exception $e)
            {
                Log::write('Zl7AiAnswerNumData model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                $data = [
                    'uid' => $uid,
                    'ai_num' => 0,
                    'total_num' => 0,
                    'use_num' => 0,
                    'admin_num' => 0,
                ];
            }
            return $data;
        });

        $resData['ai_num'] = max($resData['ai_num'] ?? 0, 0);
        $resData['admin_num'] = max($resData['admin_num'] ?? 0, 0);

        return $resData;
    }

    public function updateData($uid, $data)
    {
        try
        {
            $this->where('uid', $uid)->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write('Zl7AiAnswerNumData model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }
}
